package com.starmark.gateway.auth.security.filter;

import cn.hutool.core.util.StrUtil;
import com.starmark.gateway.auth.security.config.GatewayProjectConfig;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author starmark
 * @date 2020/5/11  下午9:29
 */
@WebFilter("/*")
@Component
@Slf4j
public class GatewayCorsWebFilter implements Filter , Ordered {


    @Autowired
    private GatewayProjectConfig gatewayProjectConfig;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        response.setHeader("Access-Control-Allow-Origin", StrUtil.join(",",gatewayProjectConfig.getAllowedOrigins()));
        response.setHeader("Access-Control-Allow-Methods", StrUtil.join(",",gatewayProjectConfig.getAllowedMethods()));
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", ""+gatewayProjectConfig.getAllowCredentials());
        response.setHeader("Access-Control-Allow-Headers",  StrUtil.join (",",gatewayProjectConfig.getAllowedHeaders()));
        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return ;
        }

        filterChain.doFilter(servletRequest,servletResponse);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
